package handler

import (
	"food-express/model"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	price := c.PostForm("price")
	desc := c.PostForm("desc")
	foodName := c.PostForm("foodName")
	if name == "" || price == "" || desc == "" || foodName == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "字段不能为空",
		})
	}
	var food model.Food
	err := model.DB.Create(&food).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
	})
}
func List(c *gin.Context) {
	id := c.PostForm("id")

	var food model.Food
	err := model.DB.Where("id=?", id).First(food).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": food,
	})
}
func Detail(c *gin.Context) {
	id := c.PostForm("id")

	var food model.Food
	err := model.DB.Where("id=?", id).First(food).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": food,
	})
}
func Page(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page + 1) * size
	var food model.Food
	err := model.DB.Where("?", offset).First(food).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
	}
	c.JSON(200, gin.H{
		"code":   200,
		"msg":    "success",
		"data":   food,
		"offset": offset,
	})
}
